import { useState, useEffect, memo, useCallback } from 'react'
import {
  DatePicker,
  Button,
  Form,
  Input,
  Select,
  Upload,
  Modal,
  Flex
} from 'antd'
import { useTranslation } from 'react-i18next'
import PicPreview from '@/components/PicPreview'
import AddTypeModal from './AddCarTypeModal'
import { PlusOutlined } from '@ant-design/icons'
import { tranlateKeyMap } from '@/config/keyMap'
import { DATEFORMATE, IMG_TYPE } from '@/config'
import { getBase64, formateDate } from '@/utils/tools'
import Toast from '@/utils/Toast'
import { uploadFile } from '@/api/config'
import dayjs from 'dayjs'
import { carAdd, cardUpdate } from '@/api/car'
import useGlobalConfig from '@/hooks/useGlobalConfig'
import { cloneDeep, isEmpty } from 'lodash'
import customParseFormat from 'dayjs/plugin/customParseFormat'

const { TextArea } = Input

const Index = ({ show = false, items, onCancel, onOk }) => {
  dayjs.extend(customParseFormat)
  const { t } = useTranslation()
  const isAdd = isEmpty(items)
  const { CAR_STATUS } = tranlateKeyMap()
  const [form] = Form.useForm()
  const { getCarTypes, carTypes, getCarBrands, carBrands } = useGlobalConfig()
  const [currentShow, setCurrentShow] = useState(false)
  const [showCarType, setShowCarType] = useState(false)
  const [fileList, setFileList] = useState([])

  const getInitialValues = useCallback(() => {
    if (isEmpty(items)) { 
      form.setFieldsValue(null)
      return
     }
    items.currentjoinTime = dayjs(items.joinTime, DATEFORMATE)
    if (items.picture) {
      const picList = items.picture.split(',').map(item => ({ url: item }))
      setFileList(picList)
    }
    form.setFieldsValue(items)
  }, [items, form])
  useEffect(() => {
    setCurrentShow(show)
    if (show) {
      getCarTypes()
      getCarBrands()
      getInitialValues()
    }
  }, [show, getCarTypes, getCarBrands, getInitialValues])

  const [showPic, setShowPic] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  const [previewTitle, setPreviewTitle] = useState('')
  const handlePicPreview = async (file) => { // 图片预览
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview)
    setShowPic(true)
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1))
  }
  // 上传图片的内容
  const beforeUploadMains = async (file) => { // 自定义上传]
    const isType = IMG_TYPE.some(item => file.type.includes(item))
    if (!isType) {
      Toast.warn('图片格式不符合!')
      return
    }
    // 
    const formData = new FormData()
    formData.set('picture', file)
    const res = await uploadFile(formData)
    setFileList([...fileList, { url: res.data }])
    return false
  }
  // 添加车类型
  const handleAddCarType = () => {
    getCarTypes()
    setShowCarType(false)
  }
  const handleClose = () => {
    setFileList([])
    form.resetFields()
    onCancel?.()
  }
  const handleOk = async () => {
    const data = await form.validateFields()
    const currentData = cloneDeep(data)
    const picture = fileList.map(item => item.url).join(',')
    const params = { ...currentData, joinTime: formateDate(data.currentjoinTime), picture }
    const fn = isAdd ? carAdd : cardUpdate
    if (!isAdd) params.carId = items.carId
    await fn(params)
    Toast.success(isAdd ? t('addSuccess') : t('updateSuccess'))
    handleClose?.()
    onOk?.()
  }

  return <Modal onCancel={handleClose} onOk={handleOk}  cancelText={t('cancel')} okText={t('save')} centered className='web-modal' title={t('car.newOrupdateCar')} open={currentShow} width='660px'>
    <Form
      form={form}
      className='web-modal-form'
      labelCol={{span: 4}}
      wrapperCol={{span: 16}}
      layout="horizontal"
      colon={false}
    >
      {/* <Form.Item name='id' label="车辆ID" rules={[{ required: true, message: '请输入车辆ID' }]}>
        <Input placeholder='请输入车辆ID'/>
      </Form.Item> */}
      {/* 车辆类型 */}
      <Form.Item label={t('car.carType')}>
        <Flex align='center'>
          <Form.Item noStyle name='carType' rules={[{ required: true, message: t('inputCarType') }]}>
            <Select disabled={!isAdd} options={carTypes} placeholder={t('inputCarType')}/>
          </Form.Item>
          <Button type="link" className='btn-516' onClick={() => setShowCarType(true)}>{t('car.addType')}</Button>
        </Flex>
      </Form.Item>
      {/* 车辆品牌 */}
      <Form.Item name='carBrand' label={t('car.carBrand')} rules={[{ required: true, message: t('inputCarBrand') }]}>
        <Select disabled={!isAdd} options={carBrands} placeholder={t('inputCarBrand')}/>
      </Form.Item>
      {/* 车辆型号 */}
      <Form.Item name='carModel' label={t('car.carModel')} rules={[{ required: true, message: t('inputCarModal'), pattern: /^[a-zA-Z0-9]+$/ig }]}>
        <Input disabled={!isAdd} placeholder={t('inputCarModal')}/>
      </Form.Item>
      {/* 入库日期 */}
      <Form.Item name='currentjoinTime' label={t('car.joinTime')} rules={[{ required: true, message: t('inputJointime') }]}>
        <DatePicker disabled={!isAdd} style={{width: '100%'}} placeholder={t('inputJointime')} maxDate={dayjs(new Date())}/>
      </Form.Item>
      {/* 发动机号 */}
      <Form.Item name='engineNumber' label={t('car.engineNumber')}>
        <Input disabled={!isAdd && items.engineNumber} placeholder={t('inputEngineNumber')}/>
      </Form.Item>
      {/* 车架号 */}
      <Form.Item name='carFrame' label={t('car.carFrame')}>
        <Input disabled={!isAdd && items.carFrame} placeholder={t('inputCarFrames')}/>
      </Form.Item>
      {/* GPS设备号 */}
      <Form.Item name='machineDevice' label={t('car.machineDevice')}>
        <Input placeholder={t('inputMachineDevice')}/>
      </Form.Item>
      {/* 上传图片 */}
      <Form.Item label={t('car.uploadFile')} wrapperCol={{span: 24}}>
        <Upload fileList={fileList} action={false} listType="picture-card" beforeUpload={beforeUploadMains} onPreview={handlePicPreview}>
          <div>
            <PlusOutlined />
            <div
            >
              {t('upload')}
            </div>
          </div>
        </Upload>
      </Form.Item>
      {/* 车辆状态 */}
      <Form.Item name='statusFlag' label={t('car.statusFlag')}>
        <Select options={CAR_STATUS} placeholder={t('inputCarStatus')}/>
      </Form.Item>
      {/* 备注 */}
      <Form.Item name='remark' label={t('car.remark')}>
        <TextArea rows={4} placeholder={t('inputPlease')}/>
      </Form.Item>
    </Form>
    <AddTypeModal show={showCarType} onCancel={() => setShowCarType(false)} onOk={handleAddCarType}/>
    <PicPreview show={showPic} previewTitle={previewTitle} previewImage={previewImage} onCancel={() => setShowPic(false)}/>
</Modal>
}

export default memo(Index)
